package projeto.finalcliente;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class ProjetoFinalClienteActivity extends Activity implements OnClickListener
{

	Button bConectar;
	EditText etDigiteRua;
	TextView tvResposta;
	Context context;

	public ProjetoFinalClienteActivity()
	{
		context = this;
	}

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.projetofinalclientelayout);
		bConectar = (Button) findViewById(R.id.bConectar);
		bConectar.setOnClickListener(this);
		etDigiteRua = (EditText) findViewById(R.id.etDigiteRua);
		tvResposta = (TextView) findViewById(R.id.tvResposta);
	}

	@Override
	public void onClick(View arg0)
	{
		new ConsultaServer().execute();
	}

	private class ConsultaServer extends AsyncTask<String, String, String>
	{

		@Override
		// essa funcao roda em um thread separada;
		protected String doInBackground(String... clientSentence)
		{
			String sentence;
			String modifiedSentence = "";
			try
			{
				Socket clientSocket = new Socket("192.168.0.101", 6789);
				DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
				BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
				sentence = etDigiteRua.getText().toString();
				outToServer.writeBytes(sentence + '\n');
				modifiedSentence = inFromServer.readLine();
				clientSocket.close();
				return modifiedSentence;
			}
			catch (Exception e)
			{

				Log.v("Projeto Final", e.toString());
				return "erro";
			}
		}

		@Override
		protected void onPostExecute(String result)
		{
			super.onPostExecute(result);
			tvResposta.setText(result);
		}
	}
}